package org.backend.canteenbackend.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.backend.canteenbackend.common.CommonResponse;
import org.backend.canteenbackend.service.AccountService;
import org.backend.canteenbackend.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/common/")
@Validated
public class CommonController {
    @Autowired
    private AccountService accountService;

    //底部
    @GetMapping("/bottom/{username}")
    public CommonResponse<AccountVO> getBottomInfo(@PathVariable String username) {
        return accountService.viewInformation(username);
    }

    //顶部
    @GetMapping("/top")
    public CommonResponse<AccountVO> getTopInfo() {
        String username = getCurrentUsername();
        return accountService.viewInformation(username);
    }

    //跳转登录倒计时
    @GetMapping("/countdown/login")
    public CommonResponse<String> countDownToLogin(HttpServletRequest request) {
        return CommonResponse.createForSuccess(request.getContextPath());
    }

    //跳转下单倒计时
    @GetMapping("/countdown/order")
    public CommonResponse<AccountVO> countDownToOrder() {
        String username = getCurrentUsername();
        return accountService.viewInformation(username);
    }

    //错误页面
    @GetMapping("/error")
    public CommonResponse<AccountVO> getErrorInfo() {
        String username = getCurrentUsername();
        return accountService.viewInformation(username);
    }

    //退出登录
    @PostMapping("/signOut")
    public CommonResponse<String> signOut() {
        return CommonResponse.createForSuccessMessage("用户登出成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }
        return authentication.getName();
    }
}
